package com.nanhang.controller;

import com.nanhang.booksearch.BookS0;
import com.nanhang.entity.Bookborrow;
import com.nanhang.entity.Bookinfo;
import com.nanhang.service.IBookborrowService;
import com.nanhang.service.IBookinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import util.PageResult;
import util.R;

import java.util.Arrays;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ymm
 * @since 2025-01-09
 */
@RestController
@RequestMapping("/bookborrow")
public class BookborrowController {

    @Autowired
    private IBookborrowService bookborrowService;

    @Autowired
    private IBookinfoService bookinfoService;

    @PostMapping("/search/{page}/{pagesize}")
    public R search(@PathVariable("page") Integer page,
                       @PathVariable("pagesize") Integer pagesize,
                       @RequestBody(required = false) BookS0 BS0) {
        PageResult<Bookborrow> res = bookborrowService.search(page, pagesize, BS0);
        return R.ok().data("res", res);
    }

    @PostMapping("/add")
    public R add(@RequestBody Bookborrow bookborrow){
        Bookinfo binfo =  bookinfoService.getById(bookborrow.getIsbn());
        binfo.setStatus("借出");
        bookinfoService.updateById(binfo);
        return bookborrowService.save(bookborrow) ? R.ok().message("添加成功！") : R.error().message("添加失败！");
    }

    @PutMapping("/update")
    public R update(@RequestBody Bookborrow bookborrow){
        return bookborrowService.updateById(bookborrow) ? R.ok().message("修改成功！") : R.error().message("修改失败！");
    }

    @DeleteMapping("/delete/{did}")
    public R delete(@PathVariable("did") String did){
        String[] split = did.split(",");
        List<String> dids = Arrays.asList(split);
        for (String string : dids) {
            int s = Integer.valueOf(string);
            Bookborrow bb = bookborrowService.getById(s);
            Bookinfo binfo = bookinfoService.getById(bb.getIsbn());
            binfo.setStatus("在库");
            bookinfoService.updateById(binfo);
        }
        return bookborrowService.removeByIds(dids) ? R.ok().message("删除成功"):R.error().message("删除失败！");
    }
}
